package middleware

import (
	"fox/enum/auth"
	"fox/enum/code"
	"fox/models"
	"fox/repositories"
	"fox/response"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// 校验header 的token

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			token          string
			tokenTime      time.Time
			userRepository *repositories.UserRepository
			user           *models.User
			err            error
		)

		userRepository = repositories.NewUserRepository()

		//请求前
		//判断header的token是否存在
		token = c.GetHeader(auth.Header)
		if token == "" {
			c.JSON(http.StatusOK, response.Response(code.TokenExpireError, "token为空", ""))
			c.Abort()
			return
		}
		//token是否有效
		if user, err = userRepository.SelectUserByToken(token); err != nil {
			c.JSON(http.StatusOK, response.Response(code.TokenExpireError, code.TokenExpireErrorStr, ""))
			c.Abort()
			return
		}
		//token是否过期
		if tokenTime, err = time.Parse("2006-01-02 15:04:05", user.TokenTime); err != nil {
			c.JSON(http.StatusOK, response.Response(code.TokenExpireError, "token时间错误", ""))
			c.Abort()
			return
		}
		if tokenTime.Before(time.Now()) {
			c.JSON(http.StatusOK, response.Response(code.TokenExpireError, code.TokenExpireErrorStr, ""))
			c.Abort()
			return
		}
		c.Set("user", user)
		c.Next()
		//请求后
	}
}
